package com.qjs.course.util;

import org.apache.log4j.Logger;
import org.codehaus.jackson.map.ObjectMapper;

import com.qjs.activity.rookie.dto.UserInfo;
import com.qjs.activity.rookie.dto.WebMessage;
import com.qjs.commom.CommonProperties;

import net.sf.json.JSONObject;

/**
 * 微信网页测试工具
 * @author Administrator
 *
 */
public class WeiXinWebUtil {
	private static Logger log =Logger.getLogger(WeiXinWebUtil.class);
	
	//获取code后，请求以下链接获取access_token以及openiD 
	private static String url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
	//拉取用户信息(需scope为 snsapi_userinfo)
	private static String userInfo_url="https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
	
	/**
	 * 通过code获取openId
	 */
	public static WebMessage getUserMessage(String code){
		WebMessage mess=null;
		String requestUrl = url.replace("APPID", CommonProperties.appid).replace("SECRET", CommonProperties.appsecret).replace("CODE", code);
		JSONObject jsonObject = WeixinUtil.httpRequest(requestUrl, "GET", null);
		String s=jsonObject.toString();
		log.error("jsonObject:"+s);
		if(jsonObject!=null){
			try {
				 ObjectMapper mapper = new ObjectMapper();  
				 mess = mapper.readValue(jsonObject.toString(), WebMessage.class); 
			//	 mess=(WebMessage) JSONObject.toBean(jsonObject,WebMessage.class); 
			} catch (Exception e) {
				log.error("获取openid失败: code:"+jsonObject.getString("errcode")+", mess:"+jsonObject.getString("errmsg"));
			}	
		}
		return mess;
	}
	
	/**
	 * 拉取用户信息(需scope为 snsapi_userinfo)
	 */
	public static UserInfo getUserInfo(String ACCESS_TOKEN,String openid){
		UserInfo user=null;
		String requestUrl = userInfo_url.replace("OPENID",openid).replace("ACCESS_TOKEN",ACCESS_TOKEN);
		JSONObject jsonObject = WeixinUtil.httpRequest(requestUrl, "GET", null);
		String s=jsonObject.toString();
		log.error("jsonObject:"+s);
		if(jsonObject!=null){
			try {
				user =new UserInfo();
				user.setCity(jsonObject.getString("city"));
				user.setCountry(jsonObject.getString("country"));
				user.setHeadimgurl(jsonObject.getString("headimgurl"));
				user.setNickname(jsonObject.getString("nickname"));
				user.setOpenid(jsonObject.getString("openid"));
				user.setSex(jsonObject.getString("sex"));
			} catch (Exception e) {
				log.error("获取userInfo失败！ code:"+jsonObject.getString("errcode")+", mess:"+jsonObject.getString("errmsg"));
			}	
		}
		return user;
	}
	
}
